<template>
  <div :class="{'dark-theme':isDark}">
    <s-nav-bar v-show="shellShow" color="#666" bg="#fff" :showHome="false">
      <div class="fc vh-c ac-nb-item">
        <van-icon name="orders-o" />
        <a href="javascript:;" @click="addBook">加入书架</a>
      </div>
      <div class="fc vh-c ac-nb-item">
        <van-icon name="wap-home-o" />
        <router-link to="/home">首页</router-link>
      </div>
    </s-nav-bar>
    <tab-bar v-show="shellShow" 
      @near="toRecent"
      @theme="isDark = !isDark" 
      @list="show = !(shellShow = show)" 
      @config="fontSizeConfig">
    </tab-bar>
    <div class="content-wrap" id="content" :style="{fontSize:fontSize+'px'}" 
      @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend" 
    >
      <div v-show="contentShow">
      <!-- 下拉加载 -->
      <pull-load :pullfresh="downPullFresh" :freshText="datalist.prev?datalist.prev.name:'已是第一章'"></pull-load>

      <!-- 文章正文 -->
      <content-wrap :title="datalist.title" :body="body"></content-wrap>
      
      <!-- 上拉加载 -->
      <pull-load :pullfresh="upPullFresh" text="上拉阅读下一章" :freshText="datalist.next?datalist.next.name:'已是最后一章'"></pull-load>
      </div>
    </div>
    <van-popup v-model="show" position="left" :style="{ width: '75%',height:'100%' }"
    @open="shellShow = false" @close="shellShow = true" >
      <span class="sec-label">共 {{datalist.count}} 章</span>
      <div class="pre-next">
        <a :class="{'not-pre-next':datalist.noprev}" href="javascript:;" @click="changeList('pre')">
          上{{listMax}}章
        </a>
        <a :class="{'not-pre-next':datalist.nonext}" href="javascript:;" @click="changeList('next')">
          下{{listMax}}章
        </a>
      </div>
      <section-list @link="changeArticle" :articleId="$route.params.id" :data="datalist.list"></section-list>
    </van-popup>
  </div>
</template>

<script>
import sNavBar from '@/components/sNavBar.vue'
import TabBar from '@/components/TabBar.vue'
import SectionList from '@/components/SectionList.vue'
import PullLoad from '@/components/PullLoad.vue'
import ContentWrap from '@/components/ContentWrap.vue'
export default {
  components:{
    sNavBar,
    TabBar,
    PullLoad,
    ContentWrap,
    SectionList
  },
  data(){
    return {
      datalist:[],
      page:0, //当前页位置
      listMax:0, //目录长度
      isDark:false, //是否夜间模式
      fontSize:15, //字号
      show:false, //是否显示侧边栏
      contentShow:false,//是否显示正文
      shellShow:true, //是否显示顶部、底部导航条

    /* 事件参数 */
      scrollType:null, //滚动类型 向上、向下、无滚动 
      initObj:null, //touchstart初始x,y坐标
      downPullFresh:false, //是否显示下拉刷新组件
      upPullFresh:false, //是否显示上拉刷新组件
      firstHandle:null, //第一次手势趋势 上下滑或者左右滑
      touchType:null, //滑动类型 上滑、下滑、右滑
      isScroll:false, //是否发生滚动
      dbtouch:{
        count:0, //点击次数
        inittime:0, //第一次点下的时间
        endtime:0, //手指抬起时间
        move:false //是否发生手指滑动
      }
    }
  },
  computed:{
    pageMax(){
      return Math.ceil(this.datalist.count/this.listMax)
    },
    body(){
      return new String(this.datalist.body).match(/\S+/g)
    }
  },
  methods:{
    fontSizeConfig(type){
      
      switch(type){
        case 'add':
          if(this.fontSize < 18){
            this.fontSize++
          }else{
            this.$toast('已是最大字号')
          }
          break;
        case 'sub':
          if(this.fontSize > 12){
            this.fontSize--
          }else{
            this.$toast('已是最小字号')
          }
          break;
      }
    },
    scrollEvent(){
      let docEl = document.documentElement;
      let scrollTop = docEl.scrollTop || document.body.scrollTop;
    
      this.isScroll = true
      if(scrollTop <= 0){
        this.scrollType = 'top'
      }else if(scrollTop >= docEl.scrollHeight-docEl.clientHeight){
        this.scrollType = 'bottom'
      }else{
        this.scrollType = null
      }
    },
    touchstart(e){
      let initX = e.changedTouches[0].clientX,
          initY = e.changedTouches[0].clientY;
      this.initObj = {initX,initY}
      let curTime = new Date().getTime()
      if(this.dbtouch.endtime != 0 && curTime - this.dbtouch.endtime>1000){
        this.dbtouch.count = 0
      }
      if(this.dbtouch.count == 0){
        this.dbtouch.inittime = curTime
      }
    
    },
    touchmove(e){
      let x= e.changedTouches[0].clientX,
          y = e.changedTouches[0].clientY,
          {initX,initY} = this.initObj,
          w =  Math.abs(x-initX), h =  Math.abs(y-initY);  
      this.dbtouch.move = true
    // 判断滑动类型
      let docEl = document.documentElement;
      if(docEl.clientHeight == docEl.scrollHeight){
        this.scrollType = 'none'
      }
      if(y-initY < -20){
        this.shellShow = false
      }
  
      if(y-initY > 20 && (this.scrollType == 'none' || (this.scrollType == 'top' && this.isScroll)) && this.firstHandle != 'horizontal'){// 向下滑
       
        this.touchType = 'down'
        this.firstHandle = 'vertical'
        this.downPullFresh = true
      }else if(y-initY < -20 && (this.scrollType == 'none' || (this.scrollType == 'bottom' && this.isScroll)) && this.firstHandle != 'horizontal'){//向上滑
        this.touchType = 'up'
        this.firstHandle = 'vertical'
        this.upPullFresh = true
      }else if(x-initX > 20 && !this.isScroll && this.firstHandle != 'vertical'){//向右滑
        this.touchType = 'right'
        this.firstHandle = 'horizontal'
      }else{
        this.upPullFresh = false
        this.downPullFresh = false
        this.touchType = null
      }

     
    },
    dbltouch(cb){
      if(this.dbtouch.move){return}
      this.dbtouch.count++
      let {count,inittime} = this.dbtouch
      let curTime = new Date().getTime()
      if(count == 2 && curTime-inittime<1000){
        cb()
      }
      this.dbtouch.endtime = curTime
    },
    touchend(){
      //双击事件
      this.dbltouch(()=>{ 
        this.shellShow = true
      })
      let {path} = this.$route;
      switch(this.touchType){
        case 'down':
          let {prev} = this.datalist
          if(!prev){
            this.downPullFresh = false
            return
          }
      
          this.contentShow = false
          this.$router.replace(`${path}?section=${prev.id}`)
          this.getSectionData((res)=>{
            let {datalist,page,pageMax,listMax} = res.data.data
            this.datalist = datalist
            this.listMax = listMax
            this.page = page
            this.contentShow = true
            this.downPullFresh = false
          })
          
          break;
        case 'up':
          let {next} = this.datalist
          if(!next){
            this.upPullFresh = false
            return
          }
          this.contentShow = false
          this.$router.replace(`${path}?section=${next.id}`)
          this.getSectionData((res)=>{
            let {datalist,page,pageMax,listMax} = res.data.data
            this.datalist = datalist
            this.listMax = listMax
            this.page = page
            this.contentShow = true
            this.upPullFresh = false
          })
          break;
        case 'right':
        
          this.show = true
          break;
      }
      this.touchType = null
      this.firstHandle = null
      this.dbtouch.move = false
      this.isScroll = false
    },
    toRecent(){
      this.$router.push('/recentread')
    },
    addBook(){
      this.$toast('未登录，请先登录')
    },
    addRecentRead(){
      let recentRead = localStorage.getItem('recentRead') || "[]"
      let jsonObj = JSON.parse(recentRead)
      let existIndex = 0
      let curbook = {}
      curbook.no = this.$route.query.section
      curbook.id = this.$route.params.id
      
      let exist = jsonObj.find((book,index) => {
        existIndex = index
        return book.id == curbook.id
      })
      if(exist){
        jsonObj[existIndex].no = curbook.no
      }else{
        jsonObj.unshift(curbook)
      }
      if(jsonObj.length>10){
        jsonObj = jsonObj.slice(0,10)
      }
      localStorage.setItem('recentRead',JSON.stringify(jsonObj))
    },
    changeList(type){
      let {noprev,nonext} = this.datalist
      
      switch(type){
        case 'pre':
          if(noprev){
            return
          }
          if(this.page>1){
            this.datalist.nonext = false
            this.page--
          }
          if(this.page==1){
            this.datalist.noprev = true
          }
          break;
        case 'next':
          if(nonext){
            return
          }
          if(this.page<this.pageMax){
            this.datalist.noprev = false
            this.page++
          }
          if(this.page==this.pageMax){
            this.datalist.nonext = true
          }

          break;
      }
      this.$http.get('/sectionlist.php',{
        params:{
          page:this.page
        }
      })
      .then((res)=>{
        this.datalist.list = res.data.data.datalist
      })
      .catch((err)=>{
        throw ('世上无难事！')
      })
    },
    getSectionData(cb){
      this.$http.get(this.$route.meta.dataURL,{
        params:{
          id:this.$route.query.section
        }
      })
      .then((res)=>{
        //更新最近阅读
        this.addRecentRead()
        cb(res)
      })
      .catch((err)=>{
        throw ('小事，问题不大！')
      })
    },
    changeArticle(){
      this.show = false
      this.contentShow = false
      this.getSectionData((res)=>{
        let {datalist,page,pageMax,listMax} = res.data.data
        if(!datalist){
          return this.$router.replace('/404')
        }
        this.datalist = datalist
        this.listMax = listMax
        this.page = page
        this.contentShow = true
      })
    }
  },
  created(){
    //请求数据
    this.getSectionData((res)=>{
      let {datalist,page,pageMax,listMax} = res.data.data
      if(!datalist){
        return this.$router.replace('/404')
      }
      this.datalist = datalist
      this.listMax = listMax
      this.page = page
      this.contentShow = true
    })
  },
  mounted(){  
    window.addEventListener('scroll', this.scrollEvent)
  },
  destroyed(){
    window.removeEventListener('scroll', this.scrollEvent)
  }
 
}
</script>

<style>
.ac-nb-item>a{
  font-size: 12PX !important;
}
.ac-nb-item{
  margin-left: 25px;
}
/* 夜间模式 */
.dark-theme .van-nav-bar,.dark-theme .tabbar,.dark-theme .set-wrap{
  background: #343434 !important;
}
.dark-theme .content-wrap{
  background: #2f2f2f;
}
.dark-theme .content-wrap{
  color: #787878;
}
.dark-theme .set-wrap>a{
  border-color: #5e5e5e;
}
.tabbar{
  background: #fff;
  color: #666;
}
/* 正文容器 */
.content-wrap{
  padding: 0 15PX;
  margin-top:-50PX;
  box-sizing: border-box;
  overflow: hidden;
  min-height: 100vh; 
  background: #f7f5f2;
}
/* 侧边栏 */
.sec-label{
  font-size: 15px;
  margin-left: 15px;
  color:#ABA499;
}
.pre-next{
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
}
.pre-next>a{
  font-size: 14px;
  border: 1px solid #ff976a ;
  color: #ff976a;
  border-radius: 5px;
  padding: 8px 35px;
}
.pre-next>a.not-pre-next{
  background: #ff976a;
  color: #fff;
}
</style>